"use client"

import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react'
import { authAPI, LoginResponse } from '@/lib/api'

interface AuthContextType {
  user: LoginResponse['user'] | null
  login: (username: string, password: string) => Promise<LoginResponse>
  logout: () => Promise<void>
  isLoading: boolean
  isAuthenticated: boolean
}

const AuthContext = createContext<AuthContextType | undefined>(undefined)

export function useAuth() {
  const context = useContext(AuthContext)
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider')
  }
  return context
}

interface AuthProviderProps {
  children: ReactNode
}

export function AuthProvider({ children }: AuthProviderProps) {
  const [user, setUser] = useState<LoginResponse['user'] | null>(null)
  const [isLoading, setIsLoading] = useState(true)

  const isAuthenticated = !!user

  // 初始化时检查session
  useEffect(() => {
    const initializeAuth = async () => {
      try {
        // 在开发环境中，先检查localStorage中是否有用户信息
        if (typeof window !== 'undefined') {
          const savedUser = localStorage.getItem('admin_user')
          if (savedUser) {
            try {
              const user = JSON.parse(savedUser)
              setUser(user)
              console.log('从localStorage恢复用户信息:', user)
              setIsLoading(false)
              return
            } catch (e) {
              console.warn('解析localStorage用户信息失败:', e)
              localStorage.removeItem('admin_user')
            }
          }
        }

        // 验证session是否有效
        const isValid = await authAPI.validateToken()
        
        if (isValid) {
          // 获取当前用户信息
          const currentUser = await authAPI.getCurrentUser()
          setUser(currentUser)
          // 保存到localStorage
          if (typeof window !== 'undefined') {
            localStorage.setItem('admin_user', JSON.stringify(currentUser))
          }
        }
      } catch (error) {
        console.error('Authentication initialization error:', error)
        // 清除localStorage中的用户信息
        if (typeof window !== 'undefined') {
          localStorage.removeItem('admin_user')
        }
      } finally {
        setIsLoading(false)
      }
    }

    initializeAuth()
  }, [])

  const login = async (username: string, password: string): Promise<LoginResponse> => {
    try {
      const response = await authAPI.login(username, password)
      
      if (response.success && response.user) {
        setUser(response.user)
        // 保存到localStorage
        if (typeof window !== 'undefined') {
          localStorage.setItem('admin_user', JSON.stringify(response.user))
          if (response.token) {
            localStorage.setItem('admin_token', response.token)
          }
        }
      }
      
      return response
    } catch (error) {
      console.error('Login error:', error)
      throw error
    }
  }

  const logout = async (): Promise<void> => {
    try {
      await authAPI.logout()
    } catch (error) {
      console.error('Logout error:', error)
    } finally {
      // 清除状态
      setUser(null)
      // 清除localStorage
      if (typeof window !== 'undefined') {
        localStorage.removeItem('admin_user')
        localStorage.removeItem('admin_token')
      }
    }
  }

  const value: AuthContextType = {
    user,
    login,
    logout,
    isLoading,
    isAuthenticated
  }

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  )
}